package org.example.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.oss.ServiceException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.common.StatusCode;
import org.example.service.ContentSecurityAuditService;
import org.springframework.stereotype.Service;
import com.aliyun.green20220302.models.VideoModerationRequest;
import com.aliyun.green20220302.models.VideoModerationResponse;
import com.aliyun.green20220302.models.VideoModerationResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.example.utils.AliOssUtil.accessKeyId;
import static org.example.utils.AliOssUtil.accessKeySecret;

/**
 * 内容安全审核
 * @author cat
 */
@Slf4j
@Service
public class ContentSecurityAuditServiceImpl implements ContentSecurityAuditService {



    /**
     * 审核文本内容
     *
     * @param contentText
     */
    @Override
    public Boolean contentAudit(String contentText) {
        Client client = this.createClient();

        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        //检测参数构造
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", contentText);

        TextModerationRequest textModerationRequest = new TextModerationRequest();
        /*
        文本检测服务 service code
        */
        textModerationRequest.setService("comment_detection");//公聊评论内容检测
        textModerationRequest.setServiceParameters(serviceParameters.toJSONString());
        try {
            // 调用方法获取检测结果。
            TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime);
            // 打印检测结果。
            if (response != null) {
                TextModerationResponseBody result = response.getBody();
                Integer code = result.getCode();
                if (code != null && code == 200) {
                    TextModerationResponseBody.TextModerationResponseBodyData data = result.getData();
                    if (StringUtils.isNotEmpty(data.getReason())) {
                        //检测到含有非法文字
                        return false;
                    } else {
                        //通过
                        return true;
                    }
                } else {
                    throw new ServiceException(StatusCode.AUDIT_FAIL.name());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 图片审核
     * @param imageUrl
     * @return
     */
    @Override
    public Boolean imageAudit(String imageUrl) {
        Client client = this.createClient();

        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        //循环图片
        String[] split = imageUrl.split(",");
        for (String image : split) {
            // 检测参数构造。
            Map<String, String> serviceParameters = new HashMap<>();
            //公网可访问的URL。
            serviceParameters.put("imageUrl", image);
            serviceParameters.put("dataId", UUID.randomUUID().toString());
            ImageModerationRequest request = new ImageModerationRequest();
            // 图片检测service: baselineCheck通用基线检测。
            request.setService("baselineCheck");
            request.setServiceParameters(JSON.toJSONString(serviceParameters));

            try {
                ImageModerationResponse response = client.imageModerationWithOptions(request, runtime);
                // 打印检测结果。
                if (response != null) {
                    ImageModerationResponseBody body = response.getBody();
                    if (body.getCode() == 200) {
                        ImageModerationResponseBody.ImageModerationResponseBodyData data = body.getData();
                        List<ImageModerationResponseBody.ImageModerationResponseBodyDataResult> results = data.getResult();
                        for (ImageModerationResponseBody.ImageModerationResponseBodyDataResult result : results) {
                            if (result.getConfidence() != null && result.getConfidence() != null) {
                                //审核拒绝
                                return false;
                            } else {
                                //审核通过
                                return true;
                            }
                        }
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }


    /**
     * 视频审核获取TaskId
     *
     * @param videoUrl
     * @return
     */
    @Override
    public String getVideoTaskId(String videoUrl) {

        Client client = this.createClient();

        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("url", videoUrl);

        VideoModerationRequest videoModerationRequest = new VideoModerationRequest();
        // 检测类型：videoDetection
        videoModerationRequest.setService("videoDetection");
        videoModerationRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            VideoModerationResponse response = client.videoModeration(videoModerationRequest);
            if (response != null) {
                VideoModerationResponseBody result = response.getBody();
                Integer code = result.getCode();
                if (200 == code) {
                    VideoModerationResponseBody.VideoModerationResponseBodyData data = result.getData();
                    return data.getTaskId();
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 初始化账号Client
     *
     * @return Client 短信操作util
     */
    public Client createClient() {
        try {


            Config config = new Config();
            //您的AccessKey ID
            config.accessKeyId = accessKeyId;
            //您的AccessKey Secret
            config.accessKeySecret = accessKeySecret;
            config.setRegionId("cn-chengdu");
            //访问的域名
            config.setEndpoint("green-cip.cn-chengdu.aliyuncs.com");
            //连接时超时时间，单位毫秒（ms）。
            config.setReadTimeout(6000);
            //读取时超时时间，单位毫秒（ms）。
            config.setConnectTimeout(3000);
            return new Client(config);
        } catch (Exception e) {
            log.error("内容安全初始化错误", e);
        }
        return null;
    }

    /**
     * 获取视频审核结果
     *
     * @param taskId
     * @return
     */
    @Override
    public Integer videoAudit(String taskId) {
        Client client = this.createClient();

        JSONObject serviceParameters = new JSONObject();
        // 提交任务时返回的taskId。
        serviceParameters.put("taskId", taskId);


        VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest();
        // 检测类型：videoDetection
        videoModerationResultRequest.setService("videoDetection");
        videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            VideoModerationResultResponse response = client.videoModerationResult(videoModerationResultRequest);
            if (response != null) {
                VideoModerationResultResponseBody result = response.getBody();
                 return result.getCode();
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 延迟获取视频审核结果
     * @param taskId
     * @return
     */
    @Override
    public String getVideoAuditResult(String taskId) {

        try {
            com.aliyun.teaopenapi.Client client = this.createVideoClient();
            com.aliyun.teaopenapi.models.Params params = createApiInfo();
            // body params
            Map<String, String> map = new HashMap<>();
            map.put("taskId", taskId);
            Map<String, Object> body = new HashMap<>();
            body.put("Service", "videoDetection");
            body.put("ServiceParameters", JSON.toJSONString(map));
            // runtime options
            RuntimeOptions runtime = new RuntimeOptions();
            com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
                    .setBody(body);
            // 返回值为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。

            //获取接口返回数据
            Map<String, ?> response = client.callApi(params, request, runtime);
            Map<String, Object> bodyMap = (Map<String, Object>) response.get("body");
            Integer code = Integer.valueOf(bodyMap.get("Code").toString());

            if (code == 200) {
                Map<String, Object> dataMap = (Map<String, Object>) bodyMap.get("Data");
                //获取审核提示信息
                Map<String, Object> auditMap = (Map<String, Object>) dataMap.get("AudioResult");
                List<Map<String,Object>> detailMap = (List<Map<String, Object>>) auditMap.get("SliceDetails");
                //请求成功
                if (detailMap.isEmpty()) {
                    //审核通过
                    return null;
                } else {
                    //返回审核不通过信息
                    Map<String, Object> riskTips = detailMap.get(0);
                    String tips = riskTips.get("RiskTips").toString();
                    return tips;
                }
            }
            return code.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 获取视频审核结果API
     * @param
     * @return OpenApi.Params
     */
    public static com.aliyun.teaopenapi.models.Params createApiInfo()  {
        com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
                // 接口名称
                .setAction("VideoModerationResult")
                // 接口版本
                .setVersion("2022-03-02")
                // 接口协议
                .setProtocol("HTTPS")
                // 接口 HTTP 方法
                .setMethod("POST")
                .setAuthType("AK")
                .setStyle("RPC")
                // 接口 PATH
                .setPathname("/")
                // 接口请求体内容格式
                .setReqBodyType("formData")
                // 接口响应体内容格式
                .setBodyType("json");
        return params;
    }


    /**
     * 初始化账号
     * @return
     * @throws Exception
     */
    private   com.aliyun.teaopenapi.Client createVideoClient() throws Exception {
        //获取账号信息


        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Green
        config.setEndpoint("green-cip.cn-chengdu.aliyuncs.com");
        return new com.aliyun.teaopenapi.Client(config);
    }
}
